import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'  // 根路径重定向到登录页
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/main',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/main/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表板', requiresAuth: true }
      },
      {
        path: 'employee/management',
        name: 'EmployeeManagement',
        component: () => import('@/views/employee/EmployeeManagement.vue'),
        meta: { title: '员工管理', requiresAuth: true }
      },
      {
        path: 'department/management',
        name: 'DepartmentManagement',
        component: () => import('@/views/department/DeptManagement.vue'),
        meta: { title: '部门管理', requiresAuth: true }
      },
      {
        path: 'notice/management',
        name: 'NoticeManagement',
        component: () => import('@/views/notice/NoticeManagement.vue'),
        meta: { title: '公告管理', requiresAuth: true }
      },
      {
        path: 'stats/leave',
        name: 'LeaveStats',
        component: () => import('@/views/stats/LeaveStats.vue'),
        meta: { title: '请假统计', requiresAuth: true }
      },
      {
        path: 'stats/dept',
        name: 'DeptStats',
        component: () => import('@/views/stats/DeptStats.vue'),
        meta: { title: '部门统计', requiresAuth: true }
      },
      {
        path: 'application/leave',
        name: 'LeaveApplication',
        component: () => import('@/views/application/LeaveApplication.vue'),
        meta: { title: '请假申请', requiresAuth: true }
      },
      {
        path: 'system/user',
        name: 'UserManagement',
        component: () => import('@/views/system/UserManagement.vue'),
        meta: { title: '用户管理', requiresAuth: true }
      }
    ]
  },
  // 通配符路由 - 捕获所有未匹配的路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 检查登录状态
router.beforeEach((to, from, next) => {
  console.log('🚀 路由导航:', {
    from: from.path,
    to: to.path,
    matched: to.matched.length
  })
  
  const token = localStorage.getItem('token')
  console.log('🔑 当前token:', token)
  
  // 如果访问的是登录页
  if (to.path === '/login') {
    // 如果已经登录，跳转到主页面
    if (token) {
      console.log('✅ 已登录，跳转到主页面')
      next('/main/dashboard')
    } else {
      console.log('🔓 未登录，允许访问登录页')
      next()
    }
  } 
  // 如果访问的是需要认证的页面
  else if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      console.log('❌ 未登录，跳转到登录页')
      next('/login')
    } else {
      console.log('✅ 已登录，允许访问')
      next()
    }
  }
  // 其他页面（如重定向路由）
  else {
    console.log('➡️ 其他路由，直接放行')
    next()
  }
})

// 路由后置守卫 - 设置页面标题
router.afterEach((to) => {
  console.log('📄 路由完成:', to.path)
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - VUE-XIAOMAI`
  } else {
    document.title = 'VUE-XIAOMAI 管理系统'
  }
})

export default router